double value ; int tenths = 0; int inc = 1; // each "1" represents one tenth while ( tenths <= 100 ) // 100 tenths is 10.0 { value = tenths/10.0 ; // be sure to divide by a double 10.0 System.out.println( "value:" + value ); tenths = tenths + inc ; } System.out.println( "done");
You might want a
double
or float
for the loop control variable.
You would add 0.1 to it each iteration.
This would nearly work,
but leads to errors.
The value 0.1 cannot be accurately represented in binary.
A loop that repeatedly adds 0.1
to a variable will accumulate errors.
Just for fun, here is a program fragment that does just that. Enter various limit amounts and see how much error there is:
If you enter a limit of 1000.0, what would be printed out if the arithmetic were perfectly accurate?